﻿using AutoMapper;
using B.S.DataBase.Myproject.Helper;
using B.S.DataBase.MyProject.Domain.Materials;
using B.S.DataBase.MyProject.Domain.Procurements;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Write.API.Applicantions.Command.ProcurementsCommand;
using Yitter.IdGenerator;

namespace T.E.ERP.Write.API.Applicantions.CommandHandler.ProcurementsCommandCommand
{
    /// <summary>
    /// 采购订单添加
    /// </summary>
    public class AddPurcersCommandHadler : IRequestHandler<AddPurcersCommand, APIResult<object>>
    {
        /// <summary>
        /// 采购订单表
        /// </summary>
        private readonly IBaseRepository<Purchaseorder> repository;
        /// <summary>
        /// 物料信息表
        /// </summary>
        private readonly IBaseRepository<Materials_Info> inforepository;

        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 记录异常
        /// </summary>
        private readonly ILogger<AddPurcersCommandHadler> logger;

        private readonly IUnitOfWork _unitOfWork;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="inforepository"></param>
        /// <param name="mapper"></param>
        public AddPurcersCommandHadler(IBaseRepository<Purchaseorder> repository, IBaseRepository<Materials_Info> inforepository, IMapper mapper, ILogger<AddPurcersCommandHadler> logger, IUnitOfWork unitOfWork)
        {
            this.repository = repository;
            this.inforepository = inforepository;
            this.mapper = mapper;
            this.logger = logger;
            this._unitOfWork = unitOfWork;
        }

        public  async Task<APIResult<object>> Handle(AddPurcersCommand request, CancellationToken cancellationToken)
        {

            APIResult<object> result = new APIResult<object>();
            //try
            //{
                AddPurcersCommand add = new AddPurcersCommand();
                add.PurchaseOrderId = request.PurchaseOrderId;
                add.DocumentCode = request.DocumentCode = YitIdHelper.NextId().ToString();
                add.DocumentStatus = request.DocumentStatus;
                add.BusinessStatus = request.BusinessStatus;
                add.BusinessType = request.BusinessType;
                add.Documentid = request.Documentid;
                add.PurchasingDe = request.PurchasingDe;
                add.Purchasingid = request.Purchasingid;
                add.Operator = request.Operator;
                add.Auditor = request.Auditor;
                add.AuditDate = request.AuditDate;
                add.MaterialData = request.MaterialData;
                add.MaterialRire = request.MaterialRire;
                add.Supid = request.Supid;
                add.ArrivalDate = request.ArrivalDate;
                add.PurchaseContract = request.PurchaseContract;
                add.RemarksInfor = request.RemarksInfor;
                var lsit = mapper.Map<Purchaseorder>(add);
                int aen = repository.Add(lsit).Result;
                if (aen > 0)
                {
                    request.materials_Infos.ForEach(x =>
                    {
                        x.SaleCode = lsit.DocumentCode;
                    });
                    int add2 = inforepository.AddRanges(request.materials_Infos).Result;
                    if (add2 > 0)
                    {
                        result.Code = APIEnum.添加成功;
                        result.Msg = APIEnum.添加成功.ToString();
                    }
                    else
                    {
                        result.Code = APIEnum.添加失败;
                        result.Msg = APIEnum.添加失败.ToString();
                    }
                }
                else
                {
                    result.Code = APIEnum.添加失败;
                    result.Msg = APIEnum.添加失败.ToString();
                }

                //    // 开始事务
                //    await _unitOfWork.BeginTransactionAsync();
                //    // 1. 添加物料信息
                //    var purchaseOrder = mapper.Map<Purchaseorder>(request);
                //    purchaseOrder.DocumentCode = YitIdHelper.NextId().ToString();
                //    await repository.Add(purchaseOrder);
                //    // 2. 添加采购订单
                //    var materialInfo = mapper.Map<Materials_Info>(request.materials_Infos);//
                //    purchaseOrder.PurchaseOrderId = materialInfo.MaterialsInfoid; // 关联物料ID
                //    await inforepository.Add(materialInfo);

                //    // 提交事务
                //    await _unitOfWork.CommitTransactionAsync();
                //}
            //    catch (Exception ex)
            //{
            //    // 回滚事务
            //    await _unitOfWork.RollbackTransactionAsync();
            //    logger.LogError(ex, "处理请求时发生错误");
            //    throw;
            //}
            return await Task.FromResult(result);
        }
    }
}
